package com.example.ktapplication.base

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.example.ktapplication.R
import com.example.ktapplication.databinding.FragmentTabViewpagerBinding
import com.google.android.material.tabs.TabLayoutMediator

abstract class TabViewpagerFragment : BaseFragment<FragmentTabViewpagerBinding>() {

    private val viewPagerAdapter by lazy {
        DynamicViewPagerAdapter(requireActivity())
    }

    private var tabData: List<Pair<String, Fragment>> = mutableListOf()

    override fun getViewBind(): FragmentTabViewpagerBinding {
        return FragmentTabViewpagerBinding.inflate(layoutInflater)
    }

    abstract fun loadData()

    override fun onViewBing() {
        loadData()
    }

    fun setupViewPager(data: List<Pair<String, Fragment>>) {
        viewPagerAdapter.clearFragment()
        binding.viewPager.adapter = viewPagerAdapter

        tabData = data
        tabData.map {
            viewPagerAdapter.addFragment(it.second)
        }

        // 数据加载完成后显示 UI
        // 绑定 TabLayout 和 ViewPager2
        TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
            tab.text = getTabTitle(viewPagerAdapter.createFragment(position))
        }.attach()
    }

    private fun getTabTitle(fragment: Fragment): String {
        var result = ""
        tabData.filter { it.second == fragment }
            .apply {
                result = get(0).first
            }
        return result
    }

    private fun showView(show: Boolean) {
        binding.tabLayout.isVisible = show
        binding.viewPager.isVisible = show
    }

    class DynamicViewPagerAdapter(fragmentActivity: FragmentActivity) :
        FragmentStateAdapter(fragmentActivity) {

        private val fragments = mutableListOf<Fragment>()

        override fun getItemCount(): Int = fragments.size

        override fun createFragment(position: Int): Fragment = fragments[position]

        // 动态添加 Fragment
        fun addFragment(fragment: Fragment) {
            fragments.add(fragment)
            notifyItemInserted(fragments.size - 1)
        }

        // 动态删除 Fragment
        fun removeFragment(position: Int) {
            if (position in fragments.indices) {
                fragments.removeAt(position)
                notifyItemRemoved(position)
            }
        }

        // 清空 Fragment
        @SuppressLint("NotifyDataSetChanged")
        fun clearFragment() {
            fragments.clear()
            notifyDataSetChanged()
        }
    }
}
